<?php
/**
 * Created by PhpStorm.
 * User: xu42
 * Date: 16-9-7
 * Time: 下午1:24
 */

namespace App\Library;

use Illuminate\Support\Facades\DB;
use Xu42\Qznjw2014\Qznjw2014 as EducationSystem;


class User
{
    /**
     * 是否已注册
     * @param $username
     * @return bool
     */
    public static function isRegister( $username )
    {
        $user = DB::table( 'users' )->where( 'username', $username )->first();

        return $user ? $user : false;
    }

    /**
     * 是否已注册
     * @param $openid
     * @return bool
     */
    public static function isRegisterByOpenid( $openid )
    {
        $user = DB::table( 'users' )->where( 'openid', $openid )->first();

        return $user ? $user : false;
    }

    /**
     * 学号密码是否正确
     * @param $username     String 学号
     * @param $password     String 密码
     * @return bool
     */
    public static function isValid( $username, $password )
    {
        $educationSystem = new EducationSystem( $username, $password );

        return $educationSystem->isValid();
    }

    /**
     * 用户绑定或更新绑定信息
     * @param $isRegister   boolean 是否已绑定
     * @param $username
     * @param $password
     * @param $openid
     * @param $mobile
     * @return string
     */
    public static function saveOrUpdate( $isRegister, $username, $realname, $password, $openid, $mobile )
    {
        if ( $isRegister ) {  // 已注册, 更新注册信息
            DB::table( 'users' )->where( 'id', $isRegister->id )->update( [
                'realname'   => $realname,
                'password'   => base64_encode( $password ),
                'mobile'     => $mobile,
                'openid'     => $openid,
                'updated_at' => date( 'Y-m-d H:i:s' )
            ] );
            $result = '更新绑定成功';
        } else {  // 未注册, 添加注册信息
            DB::table( 'users' )->insert( [
                'username'   => $username,
                'realname'   => $realname,
                'password'   => base64_encode( $password ),
                'mobile'     => $mobile,
                'openid'     => $openid,
                'created_at' => date( 'Y-m-d H:i:s' )
            ] );
            $result = '绑定成功';
        }

//        dispatch( new \App\Jobs\SaveStudentUserInfoJob( $username, $password, $openid, $isRegister ) );
        return $result;
    }

}